﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Environment.Extensions;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Rework.CommerceHistory.Models;
using Orchard.Data;
using Orchard.Roles.Models;
using Orchard;
using Orchard.UI.Notify;
using Orchard.Localization;
using Rework.CommerceHistory.Rules;

namespace Rework.CommerceHistory.Handlers {
    [OrchardFeature("Rework.CommerceHistory")]
    public class CommerceHistoryHandler : ContentHandler {
        private readonly IRepository<UserRolesPartRecord> _userRolesRepository;
        private readonly IRepository<CommerceProductRolesRecord> _productRolesRepository;
        private readonly INotifier _notifier;
        private readonly IRulesManager _rulesManager;

        public CommerceHistoryHandler(
            IRepository<CommerceHistoryPartRecord> repository
            , IRulesManager rulesManager
            ) {
            Filters.Add(StorageFilter.For(repository));
             
            // Every time a product makes it to the history, we want to trigger off a rule
            //  This would allow for the sending of emails and a lot of other things
            _rulesManager = rulesManager;
            // Trigger rules event OnCreated
            OnCreated<CommerceHistoryPart>(
                (context, part) => 
                    _rulesManager.TriggerEvent("CommerceHistory", "Created", 
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));
            // Trigger rules event OnUpdated
            //   Cannot use OnUpdated as it seems the event has passed - throws an error
            OnUpdated<CommerceHistoryPart>(
                (context, part) => 
                    _rulesManager.TriggerEvent("CommerceHistory", "Updated",
                    () => new Dictionary<string, object> { { "Content", context.ContentItem } }));
        }

        public Localizer T { get; set; }
    }

}